﻿

@using SubstrateHelper.Data;
@using SubstrateHelper.Models;
@using ProcessBase.Models;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using System.Timers;

@inject SubstrateHelperDbContext Db
@inject MessageService MessageService

<h4>NC订单导入</h4>
<hr class="bg-primary" style="height:5px;" />
<div class="container-fluid">
    @if (Loaded)
    {

        <div class="row justify-content-end">
            <h4 class="text-primary">共选择<strong class="text-danger">@SelectedCount</strong>条订单</h4>
            <button class="btn btn-primary ml-5 mr-10 mb-1" @onclick="OnInput">导入</button>
        </div>
        <div class="row mt-2">
            <Table TItem="ProcessBase.Models.V_MES_HX_MO" @ref="TheTable"
                   IsPagination="true" PageItemsSource="@PageItemsSource"
                   IsStriped="true" IsBordered="true"
                   ShowToolbar="false" IsMultipleSelect="true"
                   ShowDeleteButton="false"
                   ShowEditButton="false"
                   Items="Items"
                   OnQueryAsync="@OnQueryAsync"
                   Height="480">

                <TableColumns>                 

                    @*基板类型*@
                    <TableColumn @bind-Field="@context.name" Sortable="true" />
                    @*订单号*@
                    <TableColumn @bind-Field="@context.vbmobillcode" Sortable="true" />
                    @*批次号*@
                    <TableColumn @bind-Field="@context.vbatchcode" Sortable="true" />
                    @*下单时间*@
                    <TableColumn @bind-Field="@context.billdate" Sortable="true" />
                    @*订单数量*@
                    <TableColumn @bind-Field="@context.nnum" Sortable="true" />

                </TableColumns>



            </Table>

        </div>




    }
    else
    {
        <h4 class="text-warning">请稍后，从NC读取数据中...</h4>
    }


</div>

<Message />
@code {

    //生产订单
    List<ProcessBase.Models.V_MES_HX_MO> Items { get; set; }

    //是否查询完毕
    bool Loaded { get; set; } = false;

    int SelectedCount { get; set; }
    System.Timers.Timer Timer;
    protected override async Task OnInitializedAsync()
    {
        await QueryOrders();

        Timer = new System.Timers.Timer(500);
        Timer.Elapsed += (o, e) =>
        {
            InvokeAsync(() =>
            {
                if (TheTable != null)
                {
                    var selected = TheTable.SelectedRows;
                    if (selected != null)
                    {
                        SelectedCount = selected.Count();

                    }
                    else
                    {
                        SelectedCount = 0;
                    }
                }
                else
                {
                    SelectedCount = 0;
                }
                StateHasChanged();
            });


        };
        Timer.Enabled = true;
    }


    private Table<ProcessBase.Models.V_MES_HX_MO> TheTable;
    protected IEnumerable<int> PageItemsSource => new int[] { 50, 100, 200 };

    private static readonly ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.V_MES_HX_MO>, string, SortOrder, IEnumerable<ProcessBase.Models.V_MES_HX_MO>>> SortLambdaCache = new ConcurrentDictionary<Type, Func<IEnumerable<ProcessBase.Models.V_MES_HX_MO>, string, SortOrder, IEnumerable<ProcessBase.Models.V_MES_HX_MO>>>();
    protected ProcessBase.Models.V_MES_HX_MO SearchModel { get; set; } = new ProcessBase.Models.V_MES_HX_MO();

    protected Task<QueryData<ProcessBase.Models.V_MES_HX_MO>> OnQueryAsync(QueryPageOptions options)
    {
        if (Items == null)
        {
            return Task.FromResult(new QueryData<ProcessBase.Models.V_MES_HX_MO>());
        }

        IEnumerable<ProcessBase.Models.V_MES_HX_MO> items = Items;

        // 过滤
        var isFiltered = false;
        if (options.Filters.Any())
        {
            items = items.Where(options.Filters.GetFilterFunc<ProcessBase.Models.V_MES_HX_MO>());
            isFiltered = true;
        }

        // 排序
        var isSorted = false;
        if (!string.IsNullOrEmpty(options.SortName))
        {
            // 外部未进行排序，内部自动进行排序处理
            var invoker = SortLambdaCache.GetOrAdd(typeof(ProcessBase.Models.V_MES_HX_MO), key => LambdaExtensions.GetSortLambda<ProcessBase.Models.V_MES_HX_MO>().Compile());
            items = invoker(items, options.SortName, options.SortOrder);
            isSorted = true;
        }

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<ProcessBase.Models.V_MES_HX_MO>()
        {
            Items = items,
            TotalCount = total,
            IsSorted = isSorted,
            IsFiltered = isFiltered
        });
    }

    private async Task OnInput()
    {

        List<string> guids = new List<string>();//便于:需要增加的统计

        using (var trans = Db.Database.BeginTransaction())
        {

            try
            {

                foreach (var item in TheTable.SelectedRows)
                {
                    //记录在订单表中
                    var order = new ProcessBase.Models.Order();
                    order.CopyFromMo(item);
                    order.Materials = "";

                    List<ProcessBase.Models.V_MES_HX_PICK_B> pick_b = null;

                    // 获得v_mes_hx_pick
                    var pick = Helpers.OracleDbHelper.GetData<ProcessBase.Models.V_MES_HX_PICK>($"select * from V_MES_HX_PICK where 工单主键 = '{item.cpmohid}'");
                    if (pick != null && pick.Count > 0)
                    {
                        //获得v_mes_hx_pcik_b
                        pick_b = Helpers.OracleDbHelper.GetData<ProcessBase.Models.V_MES_HX_PICK_B>($"select * from V_MES_HX_PICK_B where 备料计划主键 = '{pick[0].BeiLiaoJiHuaID}'");
                    }

                    if (pick_b == null)//注意：有可能有不用备料的订单
                    {
                        pick_b = new List<V_MES_HX_PICK_B>();
                    }






                    if (pick_b.Count > 0)
                    {



                        foreach (var b in pick_b)
                        {

                            string guid = Guid.NewGuid().ToString();
                            guids.Add(guid);
                            var date = DateTime.Now.Date;
                            Record record;
                            string inputLot = null;
                            string outputLot = null;
                            double inputQuantity = 0;
                            double outputQuantity = 0;
                            string xinghao = null;
                            string daima = null;
                            string mingcheng = null;

                            //
                            order.Materials += $"{b.ChanPinBianMa}:{b.XingHao}:{b.ChanPinMingCheng}:{b.KuCunPiCiHao}:{b.JiHuaChuKuShuLiang},";

                            inputLot= b.KuCunPiCiHao;
                            outputLot = b.KuCunPiCiHao;//主批号-来料标识
                            if (b.JiHuaChuKuShuLiang != null)
                            {
                                inputQuantity = outputQuantity = double.Parse(b.JiHuaChuKuShuLiang.ToString());
                            }
                            else
                            {
                                inputQuantity = outputQuantity = 0;
                            }

                            xinghao= b.XingHao;
                            daima= b.ChanPinBianMa;
                            mingcheng= b.ChanPinMingCheng;

                            //领料记录
                            //进站日期
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "进站日期";
                            record.DateTimeValue = date;
                            Db.Records.Add(record);

                            //出站日期
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "出站日期";
                            record.DateTimeValue = date;
                            Db.Records.Add(record);

                            //来料标识
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "来料标识";
                            record.StringValue = inputLot;
                            Db.Records.Add(record);

                            //产出标识
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "产出标识";
                            record.StringValue = outputLot;
                            Db.Records.Add(record);

                            //来料数量
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "来料数量";
                            record.NumberValue = inputQuantity;
                            Db.Records.Add(record);

                            //产出数量
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "产出数量";
                            record.NumberValue = outputQuantity;
                            Db.Records.Add(record);

                            //操作员
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "操作员";
                            record.StringValue = "NC导入";
                            Db.Records.Add(record);

                            //设备
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "设备";
                            record.StringValue = null;
                            Db.Records.Add(record);

                            //备注
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "备注";
                            record.StringValue = null;
                            Db.Records.Add(record);

                            //生产订单号
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "生产订单号";
                            record.StringValue = item.vbmobillcode;
                            Db.Records.Add(record);

                            //主批号
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "主批号";
                            record.StringValue = item.vbatchcode;
                            Db.Records.Add(record);

                            //材料型号
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "材料型号";
                            record.StringValue = xinghao;
                            Db.Records.Add(record);

                            //材料代码
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "材料代码";
                            record.StringValue = daima;
                            Db.Records.Add(record);

                            //材料名称
                            record = new Record();
                            record.Date = date;
                            record.Guid = guid;
                            record.ProcessName = "00#领料";
                            record.ParameterName = "材料名称";
                            record.StringValue = mingcheng;
                            Db.Records.Add(record);

                        }
                    }
                    else//注意：有可能有不用备料的订单
                    {
                        string guid = Guid.NewGuid().ToString();
                        guids.Add(guid);
                        var date = DateTime.Now.Date;
                        Record record;
                        string inputLot = null;
                        string outputLot = Guid.NewGuid().ToString();//为了兼容性，如果不备料，则产出：产出标识=随机GUID；产生数量=0
                        double inputQuantity = 0;
                        double outputQuantity = 0;
                        string xinghao = null;
                        string daima = null;
                        string mingcheng = null;

                        //领料记录
                        //进站日期
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "进站日期";
                        record.DateTimeValue = date;
                        Db.Records.Add(record);

                        //出站日期
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "出站日期";
                        Db.Records.Add(record);

                        //来料标识
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "来料标识";
                        record.StringValue = inputLot;
                        Db.Records.Add(record);

                        //产出标识
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "产出标识";
                        record.StringValue = outputLot;
                        Db.Records.Add(record);

                        //来料数量
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "来料数量";
                        record.NumberValue = inputQuantity;
                        Db.Records.Add(record);

                        //产出数量
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "产出数量";
                        record.NumberValue = outputQuantity;
                        Db.Records.Add(record);

                        //操作员
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "操作员";
                        record.StringValue = "NC导入";
                        Db.Records.Add(record);

                        //设备
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "设备";
                        record.StringValue = null;
                        Db.Records.Add(record);

                        //备注
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "备注";
                        record.StringValue = null;
                        Db.Records.Add(record);

                        //生产订单号
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "生产订单号";
                        record.StringValue = item.vbmobillcode;
                        Db.Records.Add(record);

                        //主批号
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "主批号";
                        record.StringValue = item.vbatchcode;
                        Db.Records.Add(record);

                        //材料型号
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "材料型号";
                        record.StringValue = xinghao;
                        Db.Records.Add(record);

                        //材料代码
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "材料代码";
                        record.StringValue = daima;
                        Db.Records.Add(record);

                        //材料名称
                        record = new Record();
                        record.Date = date;
                        record.Guid = guid;
                        record.ProcessName = "00#领料";
                        record.ParameterName = "材料名称";
                        record.StringValue = mingcheng;
                        Db.Records.Add(record);
                    }

                    //生产订单记录
                    Db.Orders.Add(order);

                    //写回FLAG
                    var re = Helpers.NCHelper.WriteMesFlag(item);
                }
                Db.SaveChanges();



                trans.Commit();


            }
            catch (Exception ex)
            {
                trans.Rollback();//数据库回滚
                MessageService?.Show(new MessageOption()
                {
                    Content = $"发生错误：{ex.Message}",
                    Icon = "fa fa-info-circle",
                    ShowDismiss = true,
                    Color = Color.Danger
                });
            }

        }

        try
        {
            Helpers.ProcessStatisticsHelper.UpdateStatistics(guids);

            MessageService?.Show(new MessageOption()
            {
                Content = $"导入数据成功",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
                Color = Color.Success
            });

            await QueryOrders();

        }
        catch(Exception ex)
        {
            MessageService?.Show(new MessageOption()
            {
                Content = $"发生错误：{ex.Message}",
                Icon = "fa fa-info-circle",
                ShowDismiss = true,
                Color = Color.Danger
            });
        }





    }


    private async Task QueryOrders()
    {
        Loaded = false;
        await Task.Run(() =>
        {
            List<ProcessBase.Models.V_MES_HX_MO> mos = new List<ProcessBase.Models.V_MES_HX_MO>();
            foreach (var sub in Db.CandidateLists.Where(x => x.Category == "基板类型").Distinct())
            {
                string sql = $"select * from V_MES_HX_MO where NAME = '{sub.Candidate}' and MESINPUTFLAG = 'N'";
                //string sql = $"select * from V_MES_HX_MO where MESINPUTFLAG = 'N'";
                var query = Helpers.OracleDbHelper.GetData<ProcessBase.Models.V_MES_HX_MO>(sql);
                if (query != null)
                {
                    mos.AddRange(query);
                }
            }

            Items = mos.OrderBy(x => x.billdate).OrderBy(x => x.name).ToList();
        });
        Loaded = true;
    }

}
